package com.cheng.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.admin.constant.Constants;
import com.cheng.admin.dao.CouponMapper;
import com.cheng.admin.model.Coupon;
import com.cheng.admin.model.CouponUser;
import com.cheng.admin.model.Order;
import com.cheng.admin.service.CouponService;
import com.cheng.admin.service.CouponUserService;
import com.cheng.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 优惠券表 服务实现类
 * </p>
 * @deprecated
 * @author 起凡
 * @since 2022-01-17
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {
    @Autowired
    CouponUserService couponUserService;

    @Override
    public void preprocess(Order order) {
        if (order.getCouponId() == null || order.getCouponId() <= 0) {
            order.setCouponPrice(BigDecimal.ZERO);
            return;
        }
        CouponUser one = couponUserService.getOne(Wrappers.<CouponUser>lambdaQuery().eq(CouponUser::getCouponId, order.getCouponId())
                .eq(CouponUser::getUserId, StpUtil.getLoginIdAsLong())
                .eq(CouponUser::getStatus, Constants.COUPON_USER_STATUS_UNUSED));
        if (one == null) {
            throw new CustomException("该优惠券已被使用");
        }
        Coupon coupon = getById(order.getCouponId());
        if (order.getOriginPrice().compareTo(coupon.getMinPrice()) >= 0) {
            if (coupon.getCouponType().equals(Constants.COUPON_TYPE_FULL_REDUCE)) {
                //
                order.setCouponPrice(coupon.getMoney());
            } else if (coupon.getCouponType().equals(Constants.COUPON_TYPE_DISCOUNT)) {
                //打折
                order.setCouponPrice(order.getOriginPrice().multiply(BigDecimal.ONE.subtract(BigDecimal.valueOf(coupon.getDiscount()).divide(BigDecimal.TEN, 2))));
            }
        }
        one.setOrderId(order.getId()).setUseTime(LocalDateTime.now());
        couponUserService.updateById(one);
    }

    @Override
    public void rollbackPreprocess(Order order) {
        if (order.getCouponId() == null) {
            return;
        }
        couponUserService.update(Wrappers.<CouponUser>lambdaUpdate().set(CouponUser::getUseTime, "1980-01-01 10:00:00")
                .set(CouponUser::getStatus, Constants.COUPON_USER_STATUS_UNUSED).set(CouponUser::getOrderId, null)
                .eq(CouponUser::getUserId, StpUtil.getLoginIdAsLong()).eq(CouponUser::getCouponId, order.getCouponId()));
    }
}
